# -*- coding : utf_8 -*-
'''
=======================================
Time : 2025/3/20 20:33
Author : 田霄汉
Email : 522989570@qq.com
File : mysql_util.py
Project : pytest_demo
=======================================
'''
import pymysql

class MysqlUtil:

    def __init__(self):
        """
        连接MySQL数据库
        :param host: 数据库IP地址
        :param port: 数据库端口
        :param user: 数据库用户名
        :param password: 数据库密码
        :param database: 数据库database
        :return: 连接数据游标cursor
        """
        # self.host = "localhost"
        # self.host = "172.168.7.64"
        self.host = "127.0.0.1"
        self.port = 3306
        self.user = "root"
        self.password = "Pytest@123"
        self.database = "pytest_demo"
        self.charset = "utf8"

    def connect_mysql(self):
        """
        连接MySQL数据库
        :return: connection, cursor
        """
        try:
            connection = pymysql.connect(host=self.host,
                                         port=self.port,
                                         user=self.user,
                                         password=self.password,
                                         database=self.database,
                                         charset=self.charset)
            cursor = connection.cursor()
            return connection, cursor
        except ConnectionError:
            print("===连接MySQL数据库失败，请检查连接信息===")

    def close_mysql(self, cursor, connection):
        """
        关闭数据库连接
        :param connection: MySQL连接
        :param cursor: MySQL游标
        :return:
        """
        try:
            cursor.close()
            connection.close()
        except IOError:
            print("===关闭MySQL数据库连接失败，请检查数据库状态===")

    def get_select_mysql(self, sql):
        """
        获取MySQL查询结果
        :param sql: MySQL查询语句
        :return: result查询结果
        """
        connection, cursor = self.connect_mysql()
        try:
            # 清除sql语句中的；和;符号
            if ";" in sql:
                sql = sql.replace(";", "")
            elif "；" in sql:
                sql = sql.replace("；", "")
            cursor.execute(sql)
            result = cursor.fetchall()
            return result
        except Exception:
            print("===执行MySQL查询语句报错===")
        finally:
            self.close_mysql(connection=connection, cursor=cursor)

    def exc_update_mysql(self, sql):
        """
        执行MySQL变更
        :param sql: MySQL变更语句
        :return: result变更结果
        """
        connection, cursor = self.connect_mysql()
        try:
            # 清除sql语句中的；和;符号
            if ";" in sql:
                sql.replace(";", "")
            elif "；" in sql:
                sql.replace("；", "")
            cursor.execute(sql)
            connection.commit()
        except Exception:
            connection.rollback()
            print("===执行修改语句MySQL报错，数据已经回滚===")
        finally:
            self.close_mysql(connection=connection, cursor=cursor)